package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.loopj.android.http.RequestParams;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.dialog.ECProgressDialog;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.AlipayInfo;
import com.yuntongxun.ecdemo.voicechat.bean.PayPalInfo;
import com.yuntongxun.ecdemo.voicechat.bean.PayResult;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.bean.WechatInfo;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.OrderInfoUtil2_0;
import com.yuntongxun.ecdemo.voicechat.util.PreferenceUtils;
import com.yuntongxun.ecdemo.voicechat.util.http.HttpStatusUtil;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.Map;

import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * 支付确认
 *
 * @author li_zhuonan
 * @version 1.0
 * @since 2016/11/21
 */

public class PaymentConfirmActivity extends BaseChatActivity implements ICommonViewUi {


    private IWXAPI api;

    public static final String PAY_TYPE = "pay_type";
    public static final String ALIPAY = "alipay";
    public static final String WECHAT = "wechat";
    public static final String PAYPAL = "paypal";
    @InjectView(R.id.pay_type_img)
    ImageView payTypeImg;
    @InjectView(R.id.pay_title_tv)
    TextView payTitleTv;
    @InjectView(R.id.coins_count)
    TextView coinsCountTv;
    @InjectView(R.id.coins_money)
    TextView coinsMoneyTv;


    private ICommonRequestPresenter iCommonRequestPresenter;
    private String pay_type = "";

    public static final String PAY_COINS = "coins";
    private String coins = "";
//    private static final String CONFIG_CLIENT_ID = "AQeXg_nfTp7fgHwT9BSOW1FODLRjL3jOLzwxJhvg7nZGy3FwANbwgqLmdf60KMYwxZYGP6RiaJa14oxe";
    private static PayPalConfiguration config ;

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    public void onEvent(PostResult postResult){
        if (EventBusTags.PAY_SUCCESS.equals(postResult.getTag())){
            finish();
        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_payment_confirm;
    }

    UserInfo userInfo;
    @Override
    protected void initViewsAndEvents() {
        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);
        api = WXAPIFactory.createWXAPI(this,null);
        api.registerApp(Contants.WECHAT_ID);



        setTitle("Payment");
        String data= PreferenceUtils.getPrefString(this, Contants.Preference.user_info,"");
        if (!data.equals("")){
            JsonHelper<UserInfo> jsonHelper = new JsonHelper<UserInfo>(UserInfo.class);
            userInfo = jsonHelper.getData(data, "result");
        }

        coins = getIntent().getStringExtra(PAY_COINS);
        pay_type = getIntent().getStringExtra(PAY_TYPE);
        coinsCountTv.setText("Buy "+coins+" Coins");
        switch (pay_type) {
            case ALIPAY:
                payTypeImg.setBackgroundResource(R.drawable.ic_alipay);
                payTitleTv.setText("Alipay");
                coinsMoneyTv.setText(coins+"RMB");
                break;
            case WECHAT:
                payTypeImg.setBackgroundResource(R.drawable.ic_wechat2);
                payTitleTv.setText("Wechat Pay");
                coinsMoneyTv.setText(coins+"RMB");
                break;
            case PAYPAL:
                payTypeImg.setBackgroundResource(R.drawable.ic_paypal);
                payTitleTv.setText("Paypal");
                toRequest(ApiConstants.EventTags.RMB_TO_USD);
                break;
        }
    }

    @OnClick(R.id.next_btn)
    public void onConfirmClick(){

        switch (pay_type){
            case ALIPAY:
                toRequest(ApiConstants.EventTags.ALIPAY);
                break;
            case WECHAT:
                toRequest(ApiConstants.EventTags.WECHAT);
                break;
            case PAYPAL:
                toRequest(ApiConstants.EventTags.PAYPAL);
                break;
        }
    }
    private static final int REQUEST_CODE_PAYMENT = 1;
    private void onPaypalPay(){
        if (payPalInfo==null) {
            return;
        }

        config = new PayPalConfiguration()
                .environment(PayPalConfiguration.ENVIRONMENT_PRODUCTION)
                .clientId(payPalInfo.getClient_id());

        Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        startService(intent);

        PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE, payPalInfo.getOrder_id());

        intent = new Intent(this, com.paypal.android.sdk.payments.PaymentActivity.class);

        // send the same configuration for restart resiliency
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        intent.putExtra(com.paypal.android.sdk.payments.PaymentActivity.EXTRA_PAYMENT, thingToBuy);

        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    private PayPalPayment getThingToBuy(String paymentIntent, String orderId) {
//        return new PayPalPayment(new BigDecimal("0.01"), "USD", "sample item",
//                paymentIntent);

        PayPalItem[] items =
                {
                        new PayPalItem("icons", 1, new BigDecimal(payPalInfo.getExchange_amount() + ""), "USD",
                                "sku-12345678"),
                };
        BigDecimal subtotal = PayPalItem.getItemTotal(items);
        BigDecimal shipping = new BigDecimal("0.00");
        BigDecimal tax = new BigDecimal("0.00");

        PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
        BigDecimal amount = subtotal.add(shipping).add(tax);
        PayPalPayment payment = new PayPalPayment(amount, "USD", "icons", paymentIntent);
        payment.items(items).paymentDetails(paymentDetails);

        //--- set other optional fields like invoice_number, custom field, and soft_descriptor
        Log.e("orderId",orderId);
        payment.custom(orderId);

        return payment;
    }

    private void onWechatPay(){
        if (wechatInfo==null) {
            return;
        }
        try{
            PayReq req = new PayReq();
            req.appId			= wechatInfo.getAppid();
            req.partnerId		= wechatInfo.getPartnerid();
            req.prepayId		= wechatInfo.getPrepayid();
            req.nonceStr		= wechatInfo.getNoncestr();
            req.timeStamp		= wechatInfo.getTimestamp();
            req.packageValue	= "Sign=WXPay";
            req.sign			= wechatInfo.getSign();
//            Toast.makeText(this, "正常调起支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        }catch(Exception e){
            Log.e("PAY_GET", "异常："+e.getMessage());
            Toast.makeText(this, "Error："+e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    private static final int SDK_PAY_FLAG = 1;
    private void onAliPay(){
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(alipayInfo.getApp_id(), alipayInfo.getBiz_content(), alipayInfo.getMethod(), alipayInfo.getNotify_url(), alipayInfo.getTimestamp(), alipayInfo.getVersion());
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//        String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE);
        String sign = alipayInfo.getSign();
//        Log.e("1",sign);
//        Log.e("2",alipayInfo.getSign());
        final String orderInfo = orderParam + "&sign=" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PaymentConfirmActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(PaymentConfirmActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        ToastUtil.showMessage("Success");
                        PostResult postResult = new PostResult();
                        postResult.setTag(EventBusTags.PAY_SUCCESS);
                        EventBus.getDefault().post(postResult);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PaymentConfirmActivity.this, "Fail", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };
//    String paymentId="";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =
                        data.getParcelableExtra(com.paypal.android.sdk.payments.PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i("paymentConfirm", confirm.toJSONObject().toString(4));
                        JSONObject object=new JSONObject(confirm.toJSONObject().toString(4));
//                        paymentId=object.getJSONObject("response").getString("id");
//                        Log.i("paymentConfirm", confirm.getPayment().toJSONObject().toString(4));
//                        toRequest(ApiConstants.EventTags.PAYPAL_URL);

                        String state=object.getJSONObject("response").getString("state");
                        if (state.equals("approved")){
                            ToastUtil.showMessage("Success");
                            PostResult postResult = new PostResult();
                            postResult.setTag(EventBusTags.PAY_SUCCESS);
                            EventBus.getDefault().post(postResult);
                            finish();
                        }

                    } catch (JSONException e) {
                        Log.e("paymentConfirm", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("paymentConfirm", "The user canceled.");
            } else if (resultCode == com.paypal.android.sdk.payments.PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(
                        "paymentConfirm",
                        "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        }
    }

    @Override
    public void toRequest(int eventTag) {

        if (eventTag==ApiConstants.EventTags.RMB_TO_USD){
            RequestParams params = new RequestParams();
            params.put("rmbAmount", coins);
            iCommonRequestPresenter.request(eventTag, mContext, ApiConstants.Urls.RMB_TO_USD, params);
            return;
        }

        RequestParams params = new RequestParams();
        params.put("accountName", userInfo.getAccountName());
        switch (eventTag){
            case  ApiConstants.EventTags.ALIPAY:
                params.put("payChannel", "ali");
                params.put("payAmount", coins+"00");
//                params.put("payAmount", coins+"");
            break;
            case  ApiConstants.EventTags.WECHAT:
                params.put("payChannel", "wx");
                params.put("payAmount", coins+"00");
//                params.put("payAmount", coins+"");
                break;
            case  ApiConstants.EventTags.PAYPAL:
                params.put("payChannel", "paypal");
                params.put("payAmount", coins);
                break;
        }

        iCommonRequestPresenter.request(eventTag, mContext, ApiConstants.Urls.ACCOUNT_PAY, params);
    }
    AlipayInfo alipayInfo;
    WechatInfo wechatInfo;
    PayPalInfo payPalInfo;
    @Override
    public void getRequestData(int eventTag, String result) {

        switch (eventTag){
            case  ApiConstants.EventTags.ALIPAY:
                alipayInfo = getAlipayInfo(result);
                onAliPay();
                break;
            case ApiConstants.EventTags.WECHAT:
                wechatInfo=getWechatInfo(result);
                onWechatPay();
                break;
            case ApiConstants.EventTags.PAYPAL:
                payPalInfo=getPaypalInfo(result);
                onPaypalPay();
                break;
            case ApiConstants.EventTags.PAYPAL_URL:
                showToastLong(HttpStatusUtil.getStatusMsg(result));
                break;
            case ApiConstants.EventTags.RMB_TO_USD:
                try{
                    JSONObject jsonObject=new JSONObject(result);
                    String usd=jsonObject.optString("result");
                    coinsMoneyTv.setText(usd+"USD");
                }catch (Exception e){
                    LogUtil.e("usd",e.toString());
                }

                break;
        }
    }

    private AlipayInfo getAlipayInfo(String result){
        JsonHelper<AlipayInfo> jsonHelper = new JsonHelper<AlipayInfo>(AlipayInfo.class);
        return jsonHelper.getData(result, "credential");
    }

    private WechatInfo getWechatInfo(String result){
        JsonHelper<WechatInfo> jsonHelper = new JsonHelper<WechatInfo>(WechatInfo.class);
        return jsonHelper.getData(result, "credential");
    }

    private PayPalInfo getPaypalInfo(String result){
        JsonHelper<PayPalInfo> jsonHelper = new JsonHelper<PayPalInfo>(PayPalInfo.class);
        return jsonHelper.getData(result, "credential");
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        showToastLong(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        showToastLong(msg);
    }

    private ECProgressDialog mPostingdialog;

    @Override
    public void isRequesting(int eventTag, boolean status) {
        if(status){
            mPostingdialog = new ECProgressDialog(this,"Waiting");
            mPostingdialog.show();
        }else{
            mPostingdialog.dismiss();
        }
    }
}
